import { createStore } from 'vuex'
import api from '@/api'

const store = createStore({
  state: {
    user: JSON.parse(localStorage.getItem('user') || 'null'),
    sessionId: localStorage.getItem('sessionId') || '',
    isLoggedIn: false
  },
  
  mutations: {
    SET_USER(state, user) {
      state.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    
    SET_SESSION_ID(state, sessionId) {
      state.sessionId = sessionId
      localStorage.setItem('sessionId', sessionId)
    },
    
    SET_LOGGED_IN(state, status) {
      state.isLoggedIn = status
    },
    
    CLEAR_AUTH(state) {
      state.user = null
      state.sessionId = ''
      state.isLoggedIn = false
      localStorage.removeItem('user')
      localStorage.removeItem('sessionId')
    }
  },
  
  actions: {
    async login({ commit }, credentials) {
      try {
        const response = await api.post('/api/auth/login', credentials)
        const { user, sessionId } = response.data.data
        
        commit('SET_USER', user)
        commit('SET_SESSION_ID', sessionId)
        commit('SET_LOGGED_IN', true)
        
        return response.data
      } catch (error) {
        throw error.response?.data?.message || '登录失败'
      }
    },
    
    async register({ commit }, userData) {
      try {
        const response = await api.post('/api/auth/register', userData)
        return response.data
      } catch (error) {
        throw error.response?.data?.message || '注册失败'
      }
    },
    
    async logout({ commit, state }) {
      try {
        if (state.sessionId) {
          await api.post('/api/auth/logout', { sessionId: state.sessionId })
        }
      } catch (error) {
        console.error('登出请求失败:', error)
      } finally {
        commit('CLEAR_AUTH')
      }
    },
    
    initializeAuth({ commit }) {
      const user = JSON.parse(localStorage.getItem('user') || 'null')
      const sessionId = localStorage.getItem('sessionId')
      
      if (user && sessionId) {
        commit('SET_USER', user)
        commit('SET_SESSION_ID', sessionId)
        commit('SET_LOGGED_IN', true)
      }
    }
  },
  
  getters: {
    isLoggedIn: state => !!state.user && !!state.sessionId,
    currentUser: state => state.user,
    sessionId: state => state.sessionId
  }
})

export default store
